package model

import (
	"gorm.io/gorm"
)

// Doctor 医生模型
type Doctor struct {
	gorm.Model
	Name                  string `gorm:"type:varchar(50);not null;comment:姓名"`
	Phone                 string `gorm:"type:varchar(11);not null;unique;comment:手机号"`
	Password              string `gorm:"type:char(64);not null;comment:密码"`
	Salt                  string `gorm:"type:char(32);not null;comment:盐"`
	Specialty             string `gorm:"type:varchar(100);comment:擅长领域"`
	Department            string `gorm:"type:varchar(50);comment:科室"`
	ConsultationScope     string `gorm:"type:varchar(200);comment:出诊范围"`
	Introduction          string `gorm:"type:text;comment:简介"`
	Title                 string `gorm:"type:varchar(50);comment:职称"`
	Hospital              string `gorm:"type:varchar(100);comment:医院"`
	AvatarUrl             string `gorm:"type:varchar(255);comment:头像URL"`
	QualificationCertUrl  string `gorm:"type:varchar(255);comment:资格证URL"`
	PracticeCertUrl       string `gorm:"type:varchar(255);comment:执业证URL"`
	AuditStatus           int    `gorm:"type:tinyint(1);not null;default:0;comment:审核状态:0-待审核,1-通过,2-驳回"`
	AuditReason           string `gorm:"type:varchar(255);comment:驳回原因"`
	Status                int    `gorm:"type:tinyint(1);not null;default:1;comment:状态:1-正常,2-禁用"`
}

// RegisterDoctor 注册医生
func (d *Doctor) RegisterDoctor(db *gorm.DB) error {
	return db.Create(&d).Error
}

// GetDoctorByPhone 根据手机号查询医生
func (d *Doctor) GetDoctorByPhone(db *gorm.DB, phone string) error {
	return db.Where("phone = ?", phone).First(&d).Error
}

// GetDoctorByID 根据ID查询医生
func (d *Doctor) GetDoctorByID(db *gorm.DB, id int64) error {
	return db.Where("id = ?", id).First(&d).Error
}

// UpdateDoctor 更新医生信息
func (d *Doctor) UpdateDoctor(db *gorm.DB) error {
	return db.Save(&d).Error
}

// GetDoctorList 获取医生列表
func GetDoctorList(db *gorm.DB, page, pageSize int, department, specialty string) ([]Doctor, int64, error) {
	var doctors []Doctor
	var total int64

	query := db.Model(&Doctor{}).Where("audit_status = ? AND status = ?", 1, 1)

	if department != "" {
		query = query.Where("department = ?", department)
	}
	if specialty != "" {
		query = query.Where("specialty LIKE ?", "%"+specialty+"%")
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 使用分页作用域
	if err := query.Scopes(Paginate(page, pageSize)).Find(&doctors).Error; err != nil {
		return nil, 0, err
	}

	return doctors, total, nil
}

